﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using cecbClasses.Data_Adapters.Project;
using cecbData;

namespace CECB
{
    /// <summary>
    /// Interaction logic for V_TemplateViwer_Window.xaml
    /// </summary>
    public partial class V_TemplateViwer_Window : Window
    {
        Func_Projects ObjProjcts;

        DSSEntities dataContext;
        private String SelectedImpactCat = "";
        private int treeViewImpactSelectedHeader = -1;
        private TreeViewItem selectedImpactTreeViewItem = null;

        public V_TemplateViwer_Window()
        {
            InitializeComponent();

            dataContext = new DSSEntities();
            ProjectAutocompleteTextBox.ItemsSource = new cecbData.DSSEntities().Projects;
            ObjProjcts = new Func_Projects();
            List<Categories> CatgryList = ObjProjcts.GetAllCatogries();
            comboBox_projCatogory.ItemsSource = CatgryList;

            List<cecbData.ProjectTypes> ProjectTypeList = ObjProjcts.GetAllProjectTypes();
            comboBox_projType.ItemsSource = ProjectTypeList;



        }

        private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {

        }


        private bool isProjectSelected = false;
        private String selectedProject = "";
        private void ProjectAutocomplete_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((AutoCompleteBox)sender).SelectedItem == null)
            {
              //  ImpactsAutocompleteTextBox.DataContext = null;
                isProjectSelected = false;
            }
            else {
                isProjectSelected = true;
                selectedProject = ((Projects)(((AutoCompleteBox)sender).SelectedItem)).proj_reference.ToString();

            }
        }

        private void comboBox_projCatogory_DropDownOpened(object sender, EventArgs e)
        {

        }

        private void comboBox_projCatogory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            comboBox_projType.SelectedIndex = -1;
            treeViewImpacts.Items.Clear();
            treeViewActivities.Items.Clear();
        }

        private void comboBox_projType_DropDownOpened(object sender, EventArgs e)
        {

        }

        private void comboBox_projType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBox_projType.SelectedIndex > -1)
            {
                try
                {
                    treeViewImpacts.Items.Clear();
                    treeViewActivities.Items.Clear();
                    String projCategoryReference = comboBox_projCatogory.SelectedValue.ToString();
                    String projectTypeRef = comboBox_projType.SelectedValue.ToString();
                    List<Templates> impactRef;


                    IQueryable<Templates> query = from c in dataContext.Templates
                                                  where c.proj_catref.Equals(projCategoryReference)
                                                  &&
                                                  c.proj_typeref.Equals(projectTypeRef)
                                                  select c;

                    impactRef = query.ToList();
                    fillImpacts(projCategoryReference, projectTypeRef);

                }
                catch (InvalidOperationException)
                { }
                catch (NullReferenceException)
                {

                }

            }
            else
            {
                MessageBox.Show("Select a project category!", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        #region Fill Impacts

        public void fillImpacts(String catref, String actref)
        {

            IQueryable<Components> qComponents = (from c in dataContext.Templates
                                                  join b in dataContext.Impacts on c.impt equals b.impt_reference
                                                  join d in dataContext.Components on b.impt_component equals d.cmpt_reference
                                                  where c.proj_catref.Equals(catref)
                                                         &&
                                                        c.proj_typeref.Equals(actref)
                                                  orderby b.impt_component
                                                  select d).Distinct();

            int y = 0;
            foreach (Components com in qComponents)
            {

                treeViewImpacts.Items.Add(new TreeViewItem()
                {
                    Header = com.cmpt_name //,
                    //   FontStyle = FontStyles.Italic,
                    //  FontWeight = FontWeights.Bold 
                });

                IQueryable<Impacts> qImpacts = from c in dataContext.Templates
                                               join b in dataContext.Impacts on c.impt equals b.impt_reference

                                               where c.proj_catref.Equals(catref)
                                                         &&
                                                        c.proj_typeref.Equals(actref) && b.impt_component.Equals(com.cmpt_reference)
                                               orderby b.impt_component
                                               select b;


                foreach (Impacts imp in qImpacts)
                {
                    ((TreeViewItem)treeViewImpacts.Items[y]).Items.Add(SetTreeViewImpacts(imp.impt_name.ToString(), imp.impt_reference.ToString()));
                    ((TreeViewItem)treeViewImpacts.Items[y]).IsExpanded = true;
                }
                y++;

            }
            //===============================================================================

            IQueryable<Activities> qActivities = (from c in dataContext.Templates
                                                  join b in dataContext.Activities on c.actref equals b.actv_reference

                                                  where c.proj_catref.Equals(catref)
                                                        &&
                                                       c.proj_typeref.Equals(actref)
                                                  orderby b.actv_phase
                                                  select b).GroupBy(b => b.actv_phase).Select(x => x.FirstOrDefault());


            int ax = 0;
            foreach (Activities act in qActivities)
            {

                treeViewActivities.Items.Add(new TreeViewItem()
                {
                    Header = act.actv_phase//,
                    // FontStyle = FontStyles.Italic,
                    // FontWeight = FontWeights.Bold
                });

                IQueryable<Activities> qImpacts = from c in dataContext.Templates
                                                  join b in dataContext.Activities on c.actref equals b.actv_reference

                                                  where c.proj_catref.Equals(catref)
                                                        &&
                                                       c.proj_typeref.Equals(actref)
                                                       && b.actv_phase.Equals(act.actv_phase)
                                                  select b;




                foreach (Activities imp in qImpacts)
                {
                    ((TreeViewItem)treeViewActivities.Items[ax]).Items.Add(SetTreeViewImpacts(imp.actv_name.ToString(), imp.actv_reference.ToString()));
                    ((TreeViewItem)treeViewActivities.Items[ax]).IsExpanded = true;
                }
                ax++;

            }



        }

        #endregion



        private TreeViewItem SetTreeViewImpacts(string text, String displyVal)
        {
            TreeViewItem item = new TreeViewItem();

            item.IsExpanded = true;

            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;

            CheckBox chb = new CheckBox();
            chb.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Label lbl = new Label();
            lbl.Name = "lblImpText";
            lbl.Content = text;

            stack.Children.Add(chb);
            stack.Children.Add(lbl);


            item.Header = stack;

            item.Foreground = Brushes.Brown;
            item.BorderBrush = Brushes.Black;
            item.FontStyle = FontStyles.Italic;
            item.Cursor = Cursors.Hand;
            item.FontSize = 13;
            item.Height = 22;
            item.DisplayMemberPath = displyVal;


            return item;
        }


        private TreeViewItem SetTreeViewActivity(string text, String displyVal)
        {


            TreeViewItem item = new TreeViewItem();
            CheckBox chb = new CheckBox();
            chb.Height = 12;
            chb.Width = 12;
            item.IsExpanded = true;

            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;


            Label lbl = new Label();
            lbl.Name = "lblImpText";
            lbl.Content = text;
            lbl.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            stack.Children.Add(chb);
            stack.Children.Add(lbl);


            item.Header = stack;

            item.Foreground = Brushes.Brown;
            item.BorderBrush = Brushes.Black;
            item.FontStyle = FontStyles.Italic;
            item.Cursor = Cursors.Hand;
            item.FontSize = 13;
            item.Height = 22;
            item.DisplayMemberPath = displyVal;


            return item;
        }

        private void comboBox_projType_DropDownOpened_1(object sender, EventArgs e)
        {
            if (comboBox_projCatogory.SelectedIndex < 0)
            {
                MessageBox.Show("Select a category", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                comboBox_projType.SelectedIndex = -1;
            }
        }

        private void ImpactsAutocompleteTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ImpactsAutocompleteTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
           
        }

        private void treeViewImpacts_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                TreeViewItem tvi = (TreeViewItem)treeViewImpacts.SelectedItem;
            SelectedImpactCat = tvi.Header.ToString();
            selectedImpactTreeViewItem = tvi;
            ImpactsAutocompleteTextBox.ItemsSource = new cecbData.DSSEntities().Impacts;
            ImpactsAutocompleteTextBox.ValueMemberPath = "impt_name";
            lblsearchacim.Content = "impacts :";
            }
            catch (Exception)
            {
                
                
            }
            //   treeViewImpactSelectedHeader =  tvi.

            //  StackPanel stp = (StackPanel)tvi.Header;
            //  Label lblText = (Label)stp.Children.OfType<Label>().First();



        }


        private void addImpactsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Impacts imp = (Impacts)ImpactsAutocompleteTextBox.SelectedItem;
                try
                {
                    ((TreeViewItem)treeViewImpacts.SelectedItem).Items.Add(SetTreeViewImpacts(imp.impt_name.ToString(), imp.impt_reference.ToString()));
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Select a impact", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (InvalidCastException)
            {
                Activities act = (Activities)ImpactsAutocompleteTextBox.SelectedItem;
                try
                {
                    ((TreeViewItem)treeViewActivities.SelectedItem).Items.Add(SetTreeViewImpacts(act.actv_name.ToString(), act.actv_reference.ToString()));
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Select a activity", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }

            finally
            {
                ImpactsAutocompleteTextBox.Text = "";
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            selectedItemCount = 0;
            GetSelectedItems(treeViewImpacts);
            GetSelectedItems(treeViewActivities);
            ImpactsAutocompleteTextBox.DataContext = null;
            if (selectedItemCount == 0) {
                MessageBox.Show(  "Select Items to remove from template", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(selectedItemCount + " Items removed from template", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }



        //void DeleteSelectedItems(TreeView root)
        //{
        //    var todelete = List<TreeViewItem>();
        //    GetSelectedItems(root.Items, todelete);
        //    foreach (var it in todelete)
        //    {
        //        var parent = it.Parent;
        //        parent.Items.Remove(it);
        //    }
        //}
        private int selectedItemCount = 0;
        void GetSelectedItems(TreeView trv)
        {
            List<TreeViewItem> deletList = new List<TreeViewItem>();

            foreach (TreeViewItem it in trv.Items)
            {
                foreach (TreeViewItem cit in it.Items)
                {
                    if ((bool)(((cit as TreeViewItem).Header as StackPanel).Children.OfType<CheckBox>().First()).IsChecked)
                    {
                         
                        deletList.Add(cit);

                    }

                }

            }

            foreach (TreeViewItem dtv in deletList)
            {

                foreach (TreeViewItem x in trv.Items)
                {
                    
                    x.Items.Remove(dtv);
                }
            }
            trv.Items.Refresh();
            selectedItemCount += deletList.Count;
        }

        private void addImpactsButton_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void treeViewActivities_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeViewItem tvi = (TreeViewItem)treeViewActivities.SelectedItem;
            SelectedImpactCat = tvi.Header.ToString();
            selectedImpactTreeViewItem = tvi;
            ImpactsAutocompleteTextBox.ItemsSource = new cecbData.DSSEntities().Activities;
            ImpactsAutocompleteTextBox.ValueMemberPath = "actv_name";
            lblsearchacim.Content = "activities :";
        }

        private void treeViewImpacts_GotFocus(object sender, RoutedEventArgs e)
        {
            lblsearchacim.Content = "impacts :";

            ImpactsAutocompleteTextBox.ItemsSource = new cecbData.DSSEntities().Impacts;
            ImpactsAutocompleteTextBox.ValueMemberPath = "impt_name";
        }

        private void treeViewActivities_GotFocus(object sender, RoutedEventArgs e)
        {
            lblsearchacim.Content = "activities :";

            ImpactsAutocompleteTextBox.ItemsSource = new cecbData.DSSEntities().Activities;
            ImpactsAutocompleteTextBox.ValueMemberPath = "actv_name";

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (isProjectSelected)
            {
                if (MessageBox.Show("You are above to save the template for ' " + ProjectAutocompleteTextBox.Text + "' project. Confirm to continue?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {


                    if ((insertImpactsAndActivities(treeViewActivities, selectedProject, 1)) && (insertImpactsAndActivities(treeViewImpacts, selectedProject, 2)))
                    {
                        //MessageBox.Show("Template saved successfully!", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                        ImpactsAutocompleteTextBox.DataContext = null;

                        if (MessageBox.Show(" Template saved successfully! , Do you need to view excell sheet?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {

                            this.Close();
                        }
                    }

                }
            }
            else
                MessageBox.Show("Select a project to apply the template!", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private bool insertImpactsAndActivities(TreeView trv, String projId, int type)
        {


            try
            {
                foreach (TreeViewItem it in trv.Items)
                {
                    foreach (TreeViewItem cit in it.Items)
                    {
                        if (type == 1)
                            new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Activities().insertProjectActivities(projId, cit.DisplayMemberPath.ToString());
                        else
                            new cecbClasses.Data_Adapters.ImpactAndActivity.Func_Impacts().insertProjectImpacts(projId, cit.DisplayMemberPath.ToString());
                    }

                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void ImpactsAutocompleteTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
          //  if (((AutoCompleteBox)sender).DataContext == null) {
           //     MessageBox.Show("Select an category in template","Message",MessageBoxButton.OK,MessageBoxImage.Error);
                e.Handled = true;
          //  }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }


<<<<<<< .mine


=======

>>>>>>> .r30669
    }
}
